/*
 * @Author: your name
 * @Date: 2020-06-02 17:43:41
 * @LastEditTime: 2020-06-04 11:09:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /yigo/src/Utils/FileManager.js
 */ 
import RNFS from 'react-native-fs';
        // cons 'http://192.168.20.9:9004/yigo/Data/OpportunityManagement/49713/WT.docx'
var uploadUrl = 'http://192.168.20.9:9004/yigo';  // For testing purposes, go to http://requestb.in/ and create your own link，测试上传路径
// var uploadUrl = 'http://192.168.40.13:8089/yigo'
// create an array of objects of the files you want to upload
// 创建一个想要上传文件的数组
/**
 * 文件上传
 */
export const uploadFiles = () => {
    
    var files = [
        {
          name: '789',
          filename: '789.mp3',
          filepath: RNFS.DocumentDirectoryPath + '/789.mp3',
          filetype: 'audio/x-m4a'
        }
      ];
      
      //上传开始回调
      var uploadBegin = (response) => {
          var jobId = response.jobId;
          console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
        };
        //上传进度回调
      var uploadProgress = (response) => {
        var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
         console.log('UPLOAD IS ' + percentage + '% DONE!');
      };

      //执行文件上传
        RNFS.uploadFiles({
            toUrl: 'http://192.168.20.9:9004/yigo',//文件上传路径
            files: files,    //上传的文件数组
            method: 'POST',    //HTTP请求方法
            headers: {
            'Accept': 'application/json',    //请求header
            },
            fields: {
            'hello': 'world',
            },
            begin: uploadBegin,    //上传开始回调
            progress: uploadProgress    //上传进度回调
        }).promise.then((response) => {//HTTP response响应
            console.log("上传信息:",response);
            alert(response.statusCode)
            
            if (response.statusCode == 200) {
                console.log('FILES UPLOADED!'); // response.statusCode状态码, response.headers响应header, response.body 响应body
            } else {
                console.log('SERVER ERROR');
            }
            })
            .catch((err) => {    //HTTP请求异常
            if(err.description === "cancelled") {
                // cancelled by user
            }
            console.log(err);
            })
}



/**
 * 文件下载
 */
export function downloadFile() {    
    /*下载文件*/
        // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
        // 图片
        // const downloadDest = `${RNFS.MainBundlePath}/${((Math.random() * 1000) | 0)}.jpg`;
        // const formUrl = 'http://img.kaiyanapp.com/c7b46c492261a7c19fa880802afe93b3.png?imageMogr2/quality/60/format/jpg';

        // 文件
        // const downloadDest = `${RNFS.MainBundlePath}/${((Math.random() * 1000) | 0)}.zip`;
        // const formUrl = 'http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip';

        // 视频
        // const downloadDest = `${RNFS.MainBundlePath}/${((Math.random() * 1000) | 0)}.mp4`;
        // http://gslb.miaopai.com/stream/SnY~bbkqbi2uLEBMXHxGqnNKqyiG9ub8.mp4?vend=miaopai&
        // https://gslb.miaopai.com/stream/BNaEYOL-tEwSrAiYBnPDR03dDlFavoWD.mp4?vend=miaopai&
        // const formUrl = 'https://gslb.miaopai.com/stream/9Q5ADAp2v5NHtQIeQT7t461VkNPxvC2T.mp4?vend=miaopai&';

        // 音频
        const downloadDest = `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.docx`;
        // http://wvoice.spriteapp.cn/voice/2015/0902/55e6fc6e4f7b9.mp3
        // const formUrl = 'http://wvoice.spriteapp.cn/voice/2015/0818/55d2248309b09.mp3';
        const formUrl =  'http://192.168.20.9:9004/yigo/Data/OpportunityManagement/49713/WT.docx'

        const options = {
            fromUrl: formUrl,
            toFile: downloadDest,
            background: true,
            begin: (res) => {
                console.log('begin', res);
                console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
            },
            progress: (res) => {

                let pro = res.bytesWritten / res.contentLength;
                console.log("下载进度:",pro);
                

                // this.setState({
                //     progressNum: pro,
                // });
            }
        };
        try {
            const ret = RNFS.downloadFile(options);
            ret.promise.then(res => {
                console.log('Success', res);

                console.log('file://' + downloadDest)

                // 例如保存图片
                CameraRoll.saveToCameraRoll(downloadDest)
                    .then(()=>{
                        Toast.showShortCenter('图片已保存到相册')
                    }).catch(()=>{
                        Toast.showShortCenter('图片保存失败')
                    })

            }).catch(err => {
                console.log('err', err);
            });
        }
        catch (e) {
            console.log(error);
        }
}